<template>
  <div class="pay-management-add views-container">
    <div class="wlm-form">
      <div class="wlm-form-header">添加支付方式</div>
      <div class="big-warning flex-row flex-align-c">
        <p>微信支付授权目录：</p>
        <el-button
          style="margin-left:0;"
          v-for="(item, index) in authorizedAddress"
          :key="index"
          type="text"
          @click="handleClipboard(item,$event)"
        >{{item}}</el-button>
      </div>
      <div class="wlm-form-content">
        <el-form
          :ref="formFormatData.key"
          :model="formFormatData.formData"
          :rules="formFormatData.rules"
          size="small"
          label-width="174px"
          class="retail-form"
          label-position="right"
        >
          <!-- <el-form-item label="微信支付授权目录">
                    <el-button style="margin-left:0;" v-for="(item, index) in authorizedAddress" :key="index" type="text" @click="handleClipboard(item,$event)">{{item}}</el-button>
                    <p class="form-help">点击复制链接</p>
                </el-form-item> -->
          <el-form-item label="支付名称">
            <el-input v-model.trim="formFormatData.formData.name">
            </el-input>
          </el-form-item>
          <el-form-item label="支付类型">
            <el-radio-group
              v-model="formFormatData.formData.type"
              :disabled="isFormEdit"
            >
              <el-radio :label="1">微信支付</el-radio>
              <el-radio :label="2">支付宝支付</el-radio>
              <el-radio :label="3">百度支付</el-radio>
              <el-radio :label="4">头条支付</el-radio>
            </el-radio-group>
            <div class="form-help">保存后不可修改，请谨慎选择</div>
          </el-form-item>
          <template v-if="formFormatData.formData.type == 1">
            <el-form-item label="商户类型">
              <el-radio-group v-model="formFormatData.formData.param.style">
                <el-radio label="1">微信支付（您是一般商户）</el-radio>
                <el-radio label="2">服务商子商户（您是子商户请选这个）</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="商户号"
              v-if="formFormatData.formData.param.style == 1"
            >
              <el-input v-model.trim="formFormatData.formData.param.mcn">
              </el-input>
              <p class="form-help">如果您是服务商的子商户，请联系您的服务商获取，如果是普通商户或服务商本身请填写自己的商户号。</p>
            </el-form-item>
            <el-form-item
              label="(H5支付)微信公众号APPID"
              v-if="formFormatData.formData.param.style == 1"
            >
              <el-input v-model.trim="formFormatData.formData.param.appid">
              </el-input>
            </el-form-item>
            <el-form-item
              label="微信支付密钥"
              v-if="formFormatData.formData.param.style == 1"
            >
              <el-input v-model.trim="formFormatData.formData.param.appkey">
              </el-input>
              <p class="form-help">如果您是服务商的子商户，请联系您的服务商获取，如果是普通商户或服务商本身请填写自己的支付密钥。</p>
            </el-form-item>
            <!-- <el-form-item v-if="formFormatData.formData.param.style == 2" label="子商户appid" >
                        <el-input v-model.trim="formFormatData.formData.param.cappid">
                        </el-input>
                    </el-form-item> -->
            <el-form-item
              label="服务商微信公众号APPID"
              v-if="formFormatData.formData.param.style == 2"
            >
              <el-input v-model.trim="formFormatData.formData.param.appid">
              </el-input>
              <p class="form-help">服务商的微信公众号APPID，如果您是服务商的子商户，请联系您的服务商获取</p>
            </el-form-item>
            <el-form-item
              v-if="formFormatData.formData.param.style == 2"
              label="子商户号"
            >
              <el-input v-model.trim="formFormatData.formData.param.cmcn">
              </el-input>
              <p class="form-help">子商户的微信支付商户号</p>
            </el-form-item>
            <el-form-item
              label="服务商商户号"
              v-if="formFormatData.formData.param.style == 2"
            >
              <el-input v-model.trim="formFormatData.formData.param.mcn">
              </el-input>
              <p class="form-help">如果您是服务商的子商户，请联系您的服务商获取，如果是普通商户或服务商本身请填写自己的商户号。</p>
            </el-form-item>
            <el-form-item
              label="服务商微信支付密钥"
              v-if="formFormatData.formData.param.style == 2"
            >
              <el-input v-model.trim="formFormatData.formData.param.appkey">
              </el-input>
              <p class="form-help">如果您是服务商的子商户，请联系您的服务商获取，如果是普通商户或服务商本身请填写自己的支付密钥。</p>
            </el-form-item>
            <el-form-item label="cert证书">
              <!-- v-if="!certhasUp" -->
              <el-upload
                class="upload-demo input-with-select fin-min-width"
                :action="pathUrl"
                :on-remove="certRemove"
                :before-remove="certbeforeRemove"
                :on-change="uploadOnChange"
                :multiple="multiple"
                :accept="accept"
                :auto-upload="false"
                :limit="1"
                :on-success="certsuccess"
                :on-exceed="certhandleExceed"
                :file-list="currentList.certfileList"
              >
                <el-button
                  size="small"
                  type="success"
                  @click="current='certfileList'"
                  plain
                >点击上传</el-button>
                <div
                  slot="tip"
                  class="el-upload__tip"
                >只能上传pem文件</div>
              </el-upload>
              <p v-if="formFormatData.formData.param.apiclient_cert_file_id"><span class="orders-green">上传证书 【已上传】</span></p>
              <p class="form-help">从商户平台上下载支付证书, 解压并取得其中的
                <el-tag type="warning">apiclient_cert.pem</el-tag>，如果您是服务商的子商户，请联系服务商获取。</p>
            </el-form-item>
            <el-form-item label="key证书">
              <!-- v-if="!keyhasUp" -->
              <el-upload
                class="upload-demo input-with-select fin-min-width"
                :action="pathUrl"
                :on-remove="keyRemove"
                :before-remove="keybeforeRemove"
                :on-change="uploadOnChange"
                :multiple="multiple"
                :accept="accept"
                :auto-upload="false"
                :limit="1"
                :on-success="keysuccess"
                :on-exceed="keyhandleExceed"
                :file-list="currentList.keyfileList"
              >
                <el-button
                  size="small"
                  @click="current='keyfileList'"
                  type="success"
                  plain
                >点击上传</el-button>
                <div
                  slot="tip"
                  class="el-upload__tip"
                >只能上传pem文件</div>
              </el-upload>
              <p v-if="formFormatData.formData.param.apiclient_key_file_id"><span class="orders-green">上传证书 【已上传】</span></p>
              <p class="form-help">从商户平台上下载支付证书, 解压并取得其中的
                <el-tag type="warning">apiclient_key.pem</el-tag>，如果您是服务商的子商户，请联系服务商获取。</p>
            </el-form-item>
            <el-form-item
              label="子商户企业付款"
              v-if="formFormatData.formData.param.style == 2"
            >
              <el-radio-group v-model="formFormatData.formData.param.sub_transfer">
                <el-radio label="0">不开启</el-radio>
                <el-radio label="1">开启</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              label="子商户支付秘钥"
              v-if="formFormatData.formData.param.sub_transfer == '1'&&formFormatData.formData.param.style == 2"
            >
              <el-input v-model.trim="formFormatData.formData.param.sub_secret">
              </el-input>
            </el-form-item>
            <el-form-item
              label="子商户cert证书"
              v-if="formFormatData.formData.param.sub_transfer == '1'&&formFormatData.formData.param.style == 2"
            >
              <el-upload
                class="upload-demo input-with-select fin-min-width"
                :action="pathUrl"
                :auto-upload="false"
                :on-remove="childCertRemove"
                :before-remove="childCertbeforeRemove"
                :multiple="multiple"
                :accept="accept"
                :limit="1"
                :on-change="uploadOnChange"
                :on-success="childCertsuccess"
                :on-exceed="childCerthandleExceed"
                :file-list="currentList.childCertfileList"
              >
                <el-button
                  size="small"
                  @click="current='childCertfileList'"
                  type="success"
                  plain
                >点击上传</el-button>
                <div
                  slot="tip"
                  class="el-upload__tip"
                >只能上传pem文件</div>
              </el-upload>
              <p v-if="formFormatData.formData.param.sub_cert"><span class="orders-green">上传证书 【已上传】</span></p>
              <p class="form-help">从商户平台上下载支付证书, 解压并取得其中的
                <el-tag type="warning">apiclient_cert.pem</el-tag>，如果您是服务商的子商户，请联系服务商获取。</p>
            </el-form-item>
            <el-form-item
              label="子商户key证书"
              v-if="formFormatData.formData.param.sub_transfer == '1'"
            >
              <el-upload
                class="upload-demo input-with-select fin-min-width"
                :action="pathUrl"
                :auto-upload="false"
                :on-remove="childKeyRemove"
                :before-remove="childKeybeforeRemove"
                :multiple="multiple"
                :accept="accept"
                :limit="1"
                :on-change="uploadOnChange"
                :on-success="childKeysuccess"
                :on-exceed="childKeyhandleExceed"
                :file-list="currentList.childKeyfileList"
              >
                <el-button
                  size="small"
                  type="success"
                  @click="current='childKeyfileList'"
                  plain
                >点击上传</el-button>
                <div
                  slot="tip"
                  class="el-upload__tip"
                >只能上传pem文件</div>
              </el-upload>
              <p v-if="formFormatData.formData.param.sub_key"><span class="orders-green">上传证书 【已上传】</span></p>
              <p class="form-help">从商户平台上下载支付证书, 解压并取得其中的
                <el-tag type="warning">apiclient_key.pem</el-tag>，如果您是服务商的子商户，请联系服务商获取。</p>
            </el-form-item>
          </template>
          <template v-if="formFormatData.formData.type == 2">
            <el-form-item label="应用id">
              <el-input v-model.trim="formFormatData.formData.param.zfid">
              </el-input>
            </el-form-item>
            <el-form-item label="支付宝公匙">
              <el-input
                type="textarea"
                :autosize="{ minRows: 4, maxRows: 4}"
                v-model.trim="formFormatData.formData.param.zfpublickey"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="应用私匙">
              <el-input
                type="textarea"
                :autosize="{ minRows: 4, maxRows: 4}"
                v-model.trim="formFormatData.formData.param.zfkey"
              >
              </el-input>
            </el-form-item>
            <!-- <el-form-item label="appid" >
                        <el-input v-model.trim="formFormatData.formData.param.zfb_appid_refund">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="rsa_private_key">
                        <el-upload class="upload-demo input-with-select fin-min-width" :action="pathUrl" :on-remove="rsaRemove" :before-remove="rsabeforeRemove" :multiple="multiple" :accept="accept" :limit="1" :on-success="rsasuccess" :on-exceed="rsahandleExceed" :file-list="rsafileList">
                            <el-button size="small" type="success" plain>点击上传</el-button>
                            <div slot="tip" class="el-upload__tip">只能上传pem文件</div>
                        </el-upload>
                        <p v-if="formFormatData.formData.param.zfb_cert_file_id"><span class="orders-green">上传证书 【已上传】</span></p>
                        <p class="form-help">从商户平台上下载支付证书, 解压并取得其中的
                            <el-tag type="warning">apiclient_key.pem</el-tag>，如果您是服务商的子商户，请联系服务商获取。</p>
                    </el-form-item> -->
          </template>
          <template v-if="formFormatData.formData.type == 3">
            <el-form-item label="应用id">
              <el-input v-model.trim="formFormatData.formData.param.dealId">
              </el-input>
            </el-form-item>
            <el-form-item label="appid">
              <el-input v-model.trim="formFormatData.formData.param.appid">
              </el-input>
            </el-form-item>
            <el-form-item label="appKey">
              <el-input v-model.trim="formFormatData.formData.param.appKey">
              </el-input>
            </el-form-item>
            <el-form-item label="商户ID">
              <el-input v-model.trim="formFormatData.formData.param.merchant_id">
              </el-input>
            </el-form-item>
            <el-form-item label="应用公匙">
              <el-input
                type="textarea"
                :autosize="{ minRows: 4, maxRows: 4}"
                v-model.trim="formFormatData.formData.param.zfpublickey"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="应用私匙">
              <el-input
                type="textarea"
                :autosize="{ minRows: 4, maxRows: 4}"
                v-model.trim="formFormatData.formData.param.zfkey"
              >
              </el-input>
            </el-form-item>
          </template>
          <template v-if="formFormatData.formData.type == 4">
            <el-form-item label="头条appid">
              <el-input v-model.trim="formFormatData.formData.param.appid">
              </el-input>
            </el-form-item>
            <el-form-item label="头条商户号">
              <el-input v-model.trim="formFormatData.formData.param.mcn">
              </el-input>
            </el-form-item>
            <el-form-item label="头条支付appkey">
              <el-input v-model.trim="formFormatData.formData.param.appkey">
              </el-input>
            </el-form-item>
            <el-form-item label="支付宝appid">
              <el-input v-model.trim="formFormatData.formData.param.zfid">
              </el-input>
            </el-form-item>
            <el-form-item label="支付宝公匙">
              <el-input
                type="textarea"
                :autosize="{ minRows: 4, maxRows: 4}"
                v-model.trim="formFormatData.formData.param.zfpublickey"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="支付宝应用私匙">
              <el-input
                type="textarea"
                :autosize="{ minRows: 4, maxRows: 4}"
                v-model.trim="formFormatData.formData.param.zfkey"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="H5支付">
              <el-select  v-model="formFormatData.formData.param.toutiaoh5pay_id" class="mincheck" placeholder="请选择">
                 <el-option label="不选择" value="">
                   </el-option>
                 <el-option v-for="item in categoryData" :key="item.id" :label="item.name" :value="`${item.id}`">
                   </el-option>
                  </el-select>
            </el-form-item>
          </template>
        </el-form>
      </div>
    </div>
    <div
      v-cloak
      class="wlm-fixed-btn flex-row flex-align-c flex-justify-c"
    >
      <el-button
        size="small"
        @click="formFormatSubmit({ router: { type: 'replace', path: '/setting/payManagement', code: 1 }})"
        type="primary"
      >保存</el-button>
      <router-link
        tag="span"
        to="/setting/payManagement"
      >
        <el-button size="small">返回</el-button>
      </router-link>
    </div>
  </div>
</template>

<script>
// import { userAdd } from '@/api/user'
import {
  paymentEdit,
  paymentGet,
  paymentIndex
} from '@/api/setting'
import {
  channelGet
} from '@/api/channel'
import Cookies from 'js-cookie'
import $axios from 'axios'
import mixins from '@/mixins/mixins'
import clipboard from '@/utils/clipboard'
export default {
  mixins: [mixins.getters('Form')],
  name: 'PayManagementAdd',
  components: {

  },
  directives: {

  },
  created() {
    this.$nextTick(() => {
      channelGet({ type: 'wechat' }).then((response) => {
        const {
          data: {
            data: msgData = []
          }
        } = response
        this.authorizedAddress = msgData.channel.wechat.authorizedAddress
        console.log(this.authorizedAddress)
      })
      paymentIndex().then((response) => {
        const {
          data: {
            data: msgData = []
          }
        } = response
        console.log(msgData, 'msgData')
        this.categoryData = msgData
      })
    })
  },
  computed: {
    pathUrl() {
      return `${Cookies.get('BASE_API') || `${process.env.BASE_API}/`}uploadFile`
    }
  },
  data() {
    return {
      categoryData: [],
      current: 'childCertfileList',
      currentList: {
        'certfileList': [],
        'keyfileList': [],
        'childCertfileList': [],
        'childKeyfileList': []
      },
      authorizedAddress: [],
      rsafileList: [],
      loading: true,
      multiple: false,
      cert: false,
      key: false,
      accept: '.pem,.key',
      formFormatData: {
        key: 'userForm',
        api: {
          editForm: {
            api: paymentGet,
            params: {
              id: ''
            }
          },
          submitForm: paymentEdit
        },
        formData: {
          name: '',
          type: 1,
          param: {
            toutiaoh5pay_id: '',
            sub_transfer: '0',
            sub_secret: '',
            style: '1',
            appid: '',
            mcn: '',
            appkey: '',
            cappid: '',
            cmcn: '',
            zfkey: '',
            zfid: '',
            zfpublickey: '',
            dealId: '',
            appKey: '',
            sub_cert: '',
            sub_key: '',
            merchant_id: '',
            apiclient_cert_file_id: '',
            apiclient_key_file_id: '',
            zfb_appid_refund: '',
            zfb_cert_file_id: ''
          }
        },
        rules: {
        }
      }
    }
  },
  methods: {
    handleClipboard(text, event) {
      clipboard(text, event)
    },
    certRemove(files, fileList) {

    },
    certbeforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    certhandleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    certsuccess(files, fileList) {
      const { code, data: [{ file_id = '' }] } = files
      if (code === 1) {
        this.formFormatData.formData.param.apiclient_cert_file_id = file_id
      }
    },
    keyRemove(files, fileList) {

    },
    // 自定义上传
    uploadOnChange(file) {
      if (file.status === 'ready') {
        file.url = URL.createObjectURL(file.raw)
        this.currentList[this.current] = [file]
        this.submitUpload()
        // console.log("uploadfile", file);
      } else if (file.status === 'fail') {
        this.$message.error('文件上传出错，请刷新重试！')
      }
    },
    submitUpload() {
      // 自定义上传函数
      // console.log(this.saveList, 'uploadOnChange')
      if (this.currentList[this.current].length > 0) {
        const _this = this
        const formData = new FormData()
        const config = {
          'Content-Type': 'multipart/form-data'
        }
        // 从选中的file对象里拿到数据
        _this.currentList[_this.current].map((item, index) => {
          // console.log('_this.config.isMore', _this.updateConfig.isMore)
          formData.append(
            `file`,
            item.raw
          )
        })
        formData.append(
          `default`,
          'local'
        )
        console.log('upload')
        $axios
          .post(_this.pathUrl, formData, config)
          .then(function(response) {
            const {
              data: {
                code, msg
              }
            } = response

            // console.log(response.data, code, msg)
            if (code === 1) {
              // console.log(response.data.data, 'response.data')
              // console.log(_this.current, '==================_this.current')
              if (_this.current === 'childCertfileList') {
                // console.log(response.data.data[0]['file_id'], '==================response.data.data[0][file_id]')
                _this.formFormatData.formData.param.sub_cert = response.data.data[0]['file_id']
              } else if (_this.current === 'childKeyfileList') {
                // console.log(response.data.data[0]['file_id'], '==================response.data.data[0][file_id]')
                _this.formFormatData.formData.param.sub_key = response.data.data[0]['file_id']
              } else if (_this.current === 'certfileList') {
                // console.log(response.data.data[0]['file_id'], '==================response.data.data[0][file_id]')
                _this.formFormatData.formData.param.apiclient_cert_file_id = response.data.data[0]['file_id']
              } else if (_this.current === 'keyfileList') {
                // console.log(response.data.data[0]['file_id'], '==================response.data.data[0][file_id]')
                _this.formFormatData.formData.param.apiclient_key_file_id = response.data.data[0]['file_id']
              }

              _this.$message({
                message: `${msg}`,
                type: 'success'
              })
            }
          })
          .catch((err) => {
            console.log(err)
            _this.$message.error('上传失败,请重新上传')
            _this.currentList[_this.current] = []
          })
      } else {
        this.$message({
          message: '请选择文件',
          type: 'error'
        })
      }
    },
    childCertRemove(files, fileList) {

    },
    childCertbeforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    childCerthandleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    childCertsuccess(files, fileList) {
      const { code, data: [{ file_id = '' }] } = files
      if (code === 1) {
        this.formFormatData.formData.param.sub_cert = file_id
      }
    },
    childKeyRemove(files, fileList) {

    },
    // ff
    keybeforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    keyhandleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    keysuccess(files, fileList) {
      const { code, data: [{ file_id = '' }] } = files
      if (code === 1) {
        this.formFormatData.formData.param.apiclient_key_file_id = file_id
      }
    },
    //
    childKeybeforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    childKeyhandleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    childKeysuccess(files, fileList) {
      const { code, data: [{ file_id = '' }] } = files
      if (code === 1) {
        this.formFormatData.formData.param.sub_key = file_id
      }
    },
    rsaRemove(files, fileList) {

    },
    rsabeforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    rsahandleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    rsasuccess(files, fileList) {
      const { code, data: [{ file_id = '' }] } = files
      if (code === 1) {
        this.formFormatData.formData.param.zfb_cert_file_id = file_id
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.pay-management-add {
}
</style>
